package com.telenav.xmpp;

import java.io.File;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;

import android.os.Build;

import com.telenav.comm.HostProvider;

public class XmppTool {

	private static XMPPConnection con = null;

	private static void openConnection() {
		try {
			ConnectionConfiguration connConfig = new ConnectionConfiguration(
					HostProvider.XMPP_SERVER_URL, 5222);
			connConfig.setSASLAuthenticationEnabled(false);

			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
				connConfig.setTruststoreType("AndroidCAStore");
				connConfig.setTruststorePassword(null);
				connConfig.setTruststorePath(null);
			} else {
				connConfig.setTruststoreType("BKS");
				String path = System.getProperty("javax.net.ssl.trustStore");
				if (path == null) {
					path = System.getProperty("java.home") + File.separator
							+ "etc" + File.separator + "security"
							+ File.separator + "cacerts.bks";
				}
				connConfig.setTruststorePath(path);

			}
			con = new XMPPConnection(connConfig);

			PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
			con.addPacketListener(new MassgePacketListener(), filter);
			con.connect();
		} catch (XMPPException xe) {
			xe.printStackTrace();
		}
	}

	public static XMPPConnection getConnection() {
		if (con == null) {
			openConnection();
		}
		else
		{
			try {
				if(!con.isConnected())
				{
					con.connect();
				}	
			} catch (XMPPException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return con;
	}

	public static void closeConnection() {
		con.disconnect();
		con = null;
	}
}
